<template>
<div class="absolute-full q-pa-sm" style="margin-top:100px">

    <FullCalendar class="fit" style="z-index:0;position:relative;border:1px solid grey;" ref="fullCalendar" :options="calendarOptions" />
    <create-task ref="createTask" :isCreateDialog="isCreateDialog" :projectinfo="projectinfo" :user="user" @update="handleCreateDialog"></create-task>
    <q-dialog persistent fixed v-model="isShotplanDialog" :maximized="$q.platform.is.mobile" position="standard" transition-show="slide-up" transition-hide="slide-down">
        <q-layout view="hHh Lpr fFf" container class="bg-dark hide-scrollbar">
            <q-header class="bg-grey-10 shadow-7">

                <q-toolbar>
                    <q-toolbar-title>创建拍摄通告</q-toolbar-title>
                    <q-space />

                    <q-btn dense flat icon="close" @click="handleCloseShotplan">
                    </q-btn>
                </q-toolbar>

            </q-header>
            <q-footer class="bg-grey-10 text-white q-pa-sm shadow-up-7">

                <q-toolbar inset>

                    <q-space></q-space>
                    <q-btn outline class="q-px-md" @click="submitShotplan"> 创建</q-btn>
                </q-toolbar>
            </q-footer>
            <q-page-container>
                <q-page padding class="bg-dark column hide-scrollbar">
                    <q-input v-model="deviceList" dark filled placeholder="输入拍摄设备" lazy-rules :rules="[(val) => (val !== null && val !== '') || '请输入拍摄设备']"></q-input>

                    <q-table ref="table" title="拍摄任务" dark class="full-width" @selection="handleTaskSelect" :data="afterTaskList" :columns="columns" row-key="taskname" selection="multiple" :selected.sync="selected" />

                </q-page>
            </q-page-container>

        </q-layout>

    </q-dialog>

</div>
</template>

<script>
import "@fullcalendar/core";
import {
    nanoid,
    customAlphabet
} from 'nanoid';
import moment from 'moment';
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import zhLocale from "@fullcalendar/core/locales/zh-cn";
import listPlugin from "@fullcalendar/list";
import resourceTimelinePlugin from '@fullcalendar/resource-timeline';
import {
    date
} from "quasar";
import {

    loadTaskList,
    loadTaskInfo,
    createShotplan

} from "assets/api/studio/progress";
export default {
    name: 'ProgressPlan',
    components: {

        FullCalendar: () => import("@fullcalendar/vue"), // make the <FullCalendar> tag available
        CreateTask: () => import('pages/studio/progress/component/component/CreateTask.vue')

    },
    props: {
        projectinfo: {
            type: Object,
        },

    },
    data() {
        return {
            pid: '',
            viewTitle: '',
            viewType: 'week-scheduler',
            clickable: false,
            isCreateDialog: false,
            calendarOptions: {
                plugins: [dayGridPlugin, interactionPlugin, timeGridPlugin, listPlugin],
                contentHeight: '100%',
                initialView: "dayGridMonth",
                headerToolbar: false,
                locale: zhLocale,
                selectable: true,
                droppable: false,
                editable: false,
                longPressDelay: 800,
                firstDay: 1,
                slotLabelFormat: {
                    hour: "2-digit",
                    minute: "2-digit",
                    meridiem: false,
                    hour12: false, // 设置时间为24小时
                },
                eventTimeFormat: {
                    // like '14:30:00'
                    hour: "2-digit",
                    minute: "2-digit",
                    meridiem: false,
                    hour12: false,
                },

                events: [],

                select: this.handleSelect,
                views: {},
                nowIndicator: true,
                eventDurationEditable: true,
                viewDidMount: this.handleViewMount,
                eventDidMount: this.handleDidMount,
                eventDrop: this.handleEventDrop,
                eventResize: this.handleResize,

                eventClick: this.handleClick
            },
            isEditPermit: false,
            isShotplanDialog: false,
            taskList: [],
            afterTaskList: [],
            columns: [{
                name: 'taskname',
                required: true,
                label: '任务名称',
                field: 'taskname',
                align: 'left',
            }, {
                name: 'stime',
                required: true,
                label: '开始时间',
                field: 'format_stime',
                align: 'left',
            }, {
                name: 'etime',
                required: true,
                label: '结束时间',
                field: 'format_etime',
                align: 'left',
            }, ],
            selected: [],
            deviceList: ''

        }
    },
    created() {
        this.pid = this.$route.params.pid;
        this.user = this.$store.state.user;
    },
    mounted() {
        setTimeout(() => {
            this.addProjectEvent();
            this.handleRight();
            // this.handleLoadTaskList();
        }, 200)

    },
    methods: {

        handleTaskSelect(item) {
            console.log(item);
            let i = item.rows[0];
            console.log(this.selected);
            if (item.added) {
                this.afterTaskList.forEach((t) => {
                    if (moment(t.stime).isSame(i.stime, 'day') && t.pt_id != i.pt_id) {
                        this.selected.push(t)
                    }
                })
            } else {

            }

        },
        handleShotplan() {
            this.isShotplanDialog = true;

            let taskList = this.taskList;
            var newList = []

            moment.locale('zh-cn')
            moment.locale('zh-cn', {
                    calendar: {
                        sameDay: '[今天] HH:mm',
                        nextDay: '[明天] HH:mm',
                        nextWeek: '[下周]dddd HH:mm ',
                        lastDay: '[昨天] HH:mm',
                        lastWeek: '[上周] dddd HH:mm ',
                        sameElse: 'MM/DD/ dddd HH:mm'
                    }
                }

            )

            taskList.forEach((i) => {
                console.log(moment(i.stime, 'x').isAfter(new Date().getTime(), 'x'));
                if (moment(i.stime, 'x').isAfter(new Date().getTime()) && i.taskType == 1 && i.isCreateShotplan == 0) {
                    i.format_stime = moment(i.stime, 'x').calendar()
                    i.format_etime = moment(i.etime, 'x').calendar()
                    newList.push(i)
                }
            })
            this.afterTaskList = newList;

        },
        submitShotplan() {
            if (this.user.right >= 4 && this.selected.length > 0) {
                if (this.deviceList.length > 0) {
                    createShotplan({
                        pid: this.pid,
                        taskList: this.selected,
                        stime: this.selected[0].stime,
                        deviceList: this.deviceList
                    }).then(res => {
                        if (res.data.code == 1) {
                            this.$message.success('创建拍摄通告成功！')
                            this.isShotplanDialog = false;
                            this.handleLoadTaskList();
                        } else {
                            this.$message.error('创建拍摄通告失败！')
                        }
                    })
                }

            }

        },
        handleCloseShotplan() {
            this.isShotplanDialog = false;

        },
        handleCreateTask() {
            if (this.isEditPermit) {
                this.isCreateDialog = true;
                let stime = moment(new Date().getTime()).format('YYYY-MM-DD HH:mm')
                let etime = moment(stime, 'YYYY-MM-DD HH:mm').add(1, 'h').format('YYYY-MM-DD HH:mm')
                this.$refs.createTask.createTask.stime = stime;
                this.$refs.createTask.createTask.etime = etime;
            }

        },

        handleCreateDialog(type) {

            if (type == 'reload') {
                this.handleLoadTaskList();

            }
            this.isCreateDialog = !this.isCreateDialog;

            // console.log(this.$date);
            // this.createProject.from = this.$date.now();
        },
        handleRight() {
            //仅项目管理员可以创建任务
            if (this.user.right >= 4) {
                this.handleEdit(true);
                this.isEditPermit = true;
                this.$refs.createTask.isEditPermit = true;

            } else {
                this.handleEdit(false);
                this.isEditPermit = false;
                this.$refs.createTask.isEditPermit = false;
            }
        },
        handleEdit(isEdit) {
            if (isEdit) {
                this.calendarOptions.editable = true;
                this.calendarOptions.droppable = true;

            } else {
                this.calendarOptions.editable = false;
                this.calendarOptions.droppable = false;

            }

        },
        addProjectEvent() {
            let calendarApi = this.$refs.fullCalendar.getApi();
            //console.log(this.projectinfo.stime, this.projectinfo.etime);
            let stime = moment(this.projectinfo.stime, 'YYYY/MM/DD').format('YYYY-MM-DD')
            let etime = moment(this.projectinfo.etime, 'YYYY/MM/DD').format('YYYY-MM-DD')
            let event = {
                id: 11,
                title: '项目开始',
                start: stime,
                resourceId: 10,
                classNames: 'bg-teal-6'
            };
            let endEvent = {
                id: 61,
                title: '项目结束',
                start: etime,
                resourceId: 60,
                classNames: 'bg-teal-6'
            }

            calendarApi.addEvent(event);
            calendarApi.addEvent(endEvent);
        },
        handleViewTitle() {
            let calendarApi = this.$refs.fullCalendar.getApi()
            let view = calendarApi.view;
            this.viewTitle = view.title;
            console.log(view.title);

            this.$emit('update', view.title)
        },
        handleScrolltoToday() {
            let now = Date.now();
            let calendarApi = this.$refs.fullCalendar.getApi();
            let val = calendarApi.view.type;
            //console.log(val);
            if (val == "timeGridWeek") {
                var duration = date.formatDate(now, 'E');
                let hour = parseInt(date.formatDate(now, 'HH'));
                if (hour == 0) {
                    var newhour = 0
                } else {
                    var newhour = hour - 1
                }
                //console.log(now);
                calendarApi.scrollToTime({
                    days: duration - 1,
                    milliseconds: newhour * 60 * 60 * 1000,
                })
            }
            if (val == "timeGridMonth") {
                var duration = date.formatDate(now, 'D')
                calendarApi.scrollToTime({
                    days: duration - 1

                })
            }
            if (val == "timeGridDay") {
                var duration = now;
                calendarApi.scrollToTime(duration)
            }

        },
        handleToday() {
            let calendarApi = this.$refs.fullCalendar.getApi();
            calendarApi.today();
            this.handleScrolltoToday()
            this.handleViewTitle();
        },
        handlePrev() {
            let calendarApi = this.$refs.fullCalendar.getApi();
            calendarApi.prev();
            this.handleViewTitle();
        },
        handleNext() {
            let calendarApi = this.$refs.fullCalendar.getApi();
            calendarApi.next();
            this.handleViewTitle();
        },
        handleViewMount(arg) {
            //console.log('view load');
            this.viewTitle = arg.view.title;
            this.$emit('update', arg.view.title)
            this.handleScrolltoToday();
            this.handleLoadTaskList()

        },
        handleViewType(val) {
            let calendarApi = this.$refs.fullCalendar.getApi();
            calendarApi.changeView(val);
            this.handleViewTitle();
            this.handleScrolltoToday();
        },

        handleSelect(ob) {
            let calendarApi = this.$refs.fullCalendar.getApi();
            console.log(ob);
            this.isCreateDialog = true;
            let stime = moment(ob.startStr).format('YYYY-MM-DD HH:mm')
            let etime = moment(ob.endStr).format('YYYY-MM-DD HH:mm')
            this.$refs.createTask.createTask.stime = stime;
            this.$refs.createTask.createTask.etime = etime;

        },
        handleClick(ob) {
            console.log(ob);

            this.$q.loading.show()
            loadTaskInfo({
                pt_id: ob.event.id
            }).then(res => {
                this.$q.loading.hide()
                console.log(res);
                if (res.data.code == 1) {
                    this.isCreateDialog = true;
                    let data = res.data.data[0]
                    this.$refs.createTask.createTask = {
                        pt_id: data.pt_id,
                        ob: ob,
                        name: data.taskname,
                        address: JSON.parse(data.taskAddress),
                        type: data.taskType,
                        remind: data.remindBefTime,
                        stime: moment(data.stime).format('YYYY-MM-DD HH:mm'),
                        etime: moment(data.etime).format('YYYY-MM-DD HH:mm'),
                        color: data.color,
                        subject: data.subject,
                        concat: data.concat,
                        description: data.description,

                        memberList: JSON.parse(data.memberlist),
                    }
                    this.$refs.createTask.selectedTaskMembers = JSON.parse(data.memberlist);

                }
            })

        },
        handleResize(ob) {
            console.log('resize', ob);

            // var resources = ob.event.getResources();
            // var resource_id = resources.map(function (resource) {
            //     return resource.id
            // })[0];
            // if (resource_id >= 20 && resource_id < 30) {
            //     var classname = 'bg-light-green-6';
            // }
            // if (resource_id >= 30 && resource_id < 40) {
            //     var classname = 'bg-blue-6';
            // }
            // if (resource_id >= 40 && resource_id < 50) {
            //     var classname = 'bg-cyan-6';
            // }
            // if (resource_id >= 50 && resource_id < 60) {
            //     var classname = 'bg-amber-6';
            // }
            // let reqdata = {
            //     pid: this.pid,
            //     plan_id: ob.event.id,
            //     title: ob.event.title,
            //     start: ob.event.startStr,
            //     end: ob.event.endStr,
            //     resourceId: parseInt(resource_id),
            //     color: classname
            // }

            // updatePlanEvent(reqdata).then(res => {
            //     //console.log(res);
            //     if (res.data.code == 1) {

            //         this.handleLoadTaskList()
            //     }
            // })
        },
        handleEventDrop(ob) {
            //console.log(ob, 'drop');
            let resource_id = ob.newResource.id;
            if (resource_id >= 20 && resource_id < 30) {
                var classname = 'bg-light-green-6';
            }
            if (resource_id >= 30 && resource_id < 40) {
                var classname = 'bg-blue-6';
            }
            if (resource_id >= 40 && resource_id < 50) {
                var classname = 'bg-cyan-6';
            }
            if (resource_id >= 50 && resource_id < 60) {
                var classname = 'bg-amber-6';
            }
            let reqdata = {
                pid: this.pid,
                plan_id: ob.event.id,
                title: ob.newResource.title,
                start: ob.event.startStr,
                end: ob.event.endStr,
                resourceId: ob.newResource.id,
                color: classname
            }
            //console.log(reqdata);
            updatePlanEvent(reqdata).then(res => {
                //console.log(res);
                if (res.data.code == 1) {
                    this.handleLoadTaskList()
                }
            })
        },
        handleLoadTaskList() {
            loadTaskList({
                pid: this.pid
            }).then(res => {
                if (res.data.code == 1) {
                    let data = res.data.data;
                    if (data.length > 0) {
                        let calendarApi = this.$refs.fullCalendar.getApi();
                        data.forEach(item => {
                            let event = {
                                id: item.pt_id,
                                title: item.taskname,
                                start: moment(item.stime, 'x').format('YYYY-MM-DD HH:mm'),
                                end: moment(item.etime, 'x').format('YYYY-MM-DD HH:mm'),
                                backgroundColor: item.color,
                                textColor: 'white'

                            }
                            let e = calendarApi.getEventById(item.pt_id);
                            //console.log(e);
                            if (e == null) {
                                calendarApi.addEvent(event)
                            } else {
                                e.remove()
                                calendarApi.addEvent(event)
                            }

                        })
                        this.taskList = data
                    }
                }
            })
        },
    }
}
</script>
